package com.atguigu.gmall.common.interceptor;

import com.atguigu.gmall.common.util.AuthContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author 李旭
 * @date 2022/1/17 15:33
 * @Description:
 *
 * 远程调用拦截器
 *
 *
 */
public class FeignInterceptor implements RequestInterceptor {



    /**
     *  //远程调用拦截器的执行方法
     * @param requestTemplate : 马上要出发的远程调用请求对象
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1:获取当前微服务的请求对象  SpringIOC容器
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if(null != servletRequestAttributes){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            if(null != request){
                //2:取出用户ID或临时用户ID
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                //3:将上面的ID设置给马上要出发的请求对象RequestTemplate
                if(!StringUtils.isEmpty(userId)){
                    requestTemplate.header("userId",userId);
                }
                if(!StringUtils.isEmpty(userTempId)){
                    requestTemplate.header("userTempId",userTempId);
                }
                //将当前请求对象的所有头内容全部一次性复制到马上出发的请求对象中
   /*             Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()){
                    String name = headerNames.nextElement();
                    String value = request.getHeader(name);
                    requestTemplate.header(name,value);
                }*/

            }
        }

    }
}
